import React, {useRef, useState, useEffect} from 'react';
// @ts-ignore
import {cloneDeep} from 'lodash';
import {connect} from 'umi';
import {ActionType, PageContainer, ProTable} from '@ant-design/pro-components';
import {Button, Modal, message, Form, Input, Alert, Select, InputNumber, Switch, Space} from 'antd';
import {PlusOutlined, MinusOutlined} from '@ant-design/icons';
import request from '@/utils/request'


const {TextArea} = Input;
const TableList: React.FC<unknown> = (props: any) => {
    const {dispatch, carList = []} = props;
    const [form] = Form.useForm();
    const [chargeForm] = Form.useForm();
    const actionRef = useRef<ActionType>();
    const [formModalOpen, setFormOpen] = useState(false);
    const [chargeModalOpen, setChargeOpen] = useState(false);
    const [chargeObj, setChargeObj] = useState<any>({});
    console.log('props', props)
    useEffect(() => {
        dispatch({
            type: 'integral/init'
        })
    }, [dispatch]);
    const hideFileModal = () => {
        setFormOpen(false);
        form.resetFields();
    }
    const hideChargeModal = () => {
        setChargeOpen(false);
        chargeForm.resetFields();
    }
    function submitChargeForm (values) {
        console.log('submitChargeForm', values);
    }
    const submitFileForm = (values: any) => {
        console.log('submitFileForm', values);
        request(
            '/api1/baseFunction/insertCarPoint',
            {
                method: 'POST',
                data: {
                    ...values
                },
            }
        ).then((response) => {
            if (response && response.code === 200) {
                message.success('操作成功');
                if (actionRef.current) {
                    actionRef.current.reload();
                    setFormOpen(false);
                    form.resetFields();
                }
            } else {
                message.warning(response?.msg)
            }
        })
    }
    function editCar(obj){
        console.log('editCar', obj);
        setFormOpen(true);
        form.setFieldsValue({
            ...obj
        });
    };
    function recharge(obj) {
        console.log('recharge', obj);
        setChargeOpen(true);
        setChargeObj(obj)
        chargeForm.setFieldsValue({
            id: obj?.id,
            operationFlag: 1
        })
    };
    function chargeBacks(obj) {
        console.log('chargeBacks', obj);
        setChargeOpen(true);
        setChargeObj(obj)
        chargeForm.setFieldsValue({
            id: obj?.id,
            operationFlag: 2
        })
    };
    const columns: any = [
        {
            title: '车辆vin',
            dataIndex: 'vin',
            // search: false
        },
        {
            title: '车牌号',
            dataIndex: 'carCode',
            // tip: '名称是唯一的 key',
        },
        {
            title: '积分余额',
            dataIndex: 'pointBalance',
            search: false,
        },
        {
            title: '手机号',
            dataIndex: 'tel',
            // tip: '名称是唯一的 key',
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueType: 'text',
            valueEnum: {
                0: {text: '启用'},
                1: {text: '停用'},
            },
            render: (text, record) => {
                // console.log('record', record);
                return (
                    <div>
                        {/*{record?.status ? <Tag color="green">启用</Tag> : <Tag color="#d9d9d9">停用</Tag>}*/}
                        <Switch
                            checked={record?.status === 0}
                            onChange={(checked) => {
                                console.log('checked', checked);
                                request(
                                    '/api1/baseFunction/editCarPointStatus',
                                    {
                                        method: 'post',
                                        data: {
                                            id: record?.id,
                                            status: record?.status ? 0 : 1
                                        }
                                    }).then((response) => {
                                    console.log('停用启用', response);
                                    if (response.code && response.code === 200){
                                        message.success(record?.status ? '启用成功' : '停用成功');
                                        actionRef.current?.reload();
                                    } else {
                                        message.warning(response?.msg)
                                    }
                                })
                            }}
                            checkedChildren="启用"
                            unCheckedChildren="停用"
                        />
                    </div>
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'ope',
            search: false,
            render: (_, record) => {
                return (
                    <Space size="middle">
                        <a onClick={() => recharge(record)} style={{color: '#316ad5'}}><PlusOutlined /> 充值</a>
                        <a onClick={() => chargeBacks(record)} style={{color: '#FF3116'}}><MinusOutlined /> 扣减</a>
                    </Space>
                )
            }
        },
    ];
    return (
        <PageContainer
            header={{
                title: '',
            }}
        >
            <ProTable<API.UserInfo>
                headerTitle="车辆积分列表"
                actionRef={actionRef}
                pagination={{defaultPageSize: 10}}
                rowKey="id"
                search={{
                    labelWidth: 120,
                }}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        icon={<PlusOutlined/>}
                        onClick={() => {
                            setFormOpen(true);
                            form.setFieldsValue({
                                chargeCarId: '',
                                carCode: ''
                            })
                        }}
                    >
                        新增车辆积分
                    </Button>
                ]}
                request={async (params, sorter, filter) => {
                    // const { data, success } = await queryUserList({
                    //   ...params,
                    //   // FIXME: remove @ts-ignore
                    //   // @ts-ignore
                    //   sorter,
                    //   filter,
                    // });
                    // return {
                    //   data: data?.list || [],
                    //   success,
                    // };
                    const cloneParams = cloneDeep(params);
                    delete cloneParams.current;
                    const {data, code} = await request('/api1/baseFunction/stationPageList', {
                        method: 'post',
                        data: {
                            ...cloneParams,
                            pageNum: params.current
                        }
                    });
                    if (code && code === 200) {
                        return {
                            data: data?.records || [],
                            success: true,
                            total: data?.total
                        };
                    }
                }}
                // request={async (params, sorter, filter) => {
                //     const cloneParams = cloneDeep(params);
                //     delete cloneParams.current;
                //     const {data, code} = await request('/api1/baseFunction/carPointPageList', {
                //         method: 'post',
                //         data: {
                //             ...cloneParams,
                //             pageNum: params.current
                //         }
                //     });
                //     if (code && code === 200) {
                //         return {
                //             data: data?.records || [],
                //             success: true,
                //             total: data?.total
                //         };
                //     }
                // }}
                columns={columns}
            />
            <Modal
                title="新增车辆积分"
                open={formModalOpen}
                width={680}
                onOk={form.submit}
                onCancel={hideFileModal}
                maskClosable={false}
                okText="确认"
                cancelText="取消"
                style={{padding: 24}}
            >
                <Alert
                    message={
                    <span>
                        提示：<span style={{fontWeight: 'bold', color: 'rgb(22, 93, 255)'}}>1元</span> 相当于 <span style={{fontWeight: 'bold', color: 'rgb(248, 172, 89)'}}>100积分</span>
                    </span>}
                    type="info"
                    showIcon
                />
                <Form
                    labelCol={{span: 4}}
                    wrapperCol={{span: 14}}
                    layout="horizontal"
                    form={form}
                    style={{maxWidth: 600, marginTop: 24}}
                    onFinish={(values) => submitFileForm(values)}
                >
                    <Form.Item
                        name="chargeCarId"
                        hidden
                   />
                    <Form.Item
                        name="carCode"
                        hidden
                    />
                    <Form.Item
                        label="目标车辆"
                        name="vin"
                        rules={[{required: true, message: '请选择车辆'}]}
                    >
                        <Select
                            // onChange={handleChange}
                            onChange={(value, option: any) => {
                                console.log('VALUE', value);
                                console.log('OPTION', option);
                                form.setFieldsValue({
                                    chargeCarId: option.chargeCarId,
                                    carCode: option.label
                                });
                                form.setFieldValue('chargeCarId', option?.chargeCarId);
                                form.setFieldValue('carCode', option?.label);
                            }}
                            options={
                                carList && carList.length ? carList.map((i:any) => {return {
                                        value: i.vin, label: i.carCode, chargeCarId: i.id
                                }}) : []}
                        />
                    </Form.Item>
                    <Form.Item
                        label="联系电话"
                        name="tel"
                        rules={[
                            {required: false, message: '请输入电话'},
                            {pattern: /^((\+|00)86)?1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur'}
                        ]}
                    >
                        <Input placeholder='请输入电话' />
                    </Form.Item>
                    <Form.Item
                        label="充值积分"
                        name="pointBalance"
                        rules={[{required: true, message: '请输入'}]}
                    >
                        <InputNumber style={{ width: '100%' }} min={0} placeholder='请输入' />
                    </Form.Item>
                    <Form.Item
                        name="remark"
                        label="备注"
                        rules={[{required: false, message: ''}]}
                    >
                        <TextArea style={{width: '350px'}}/>
                    </Form.Item>
                </Form>
            </Modal>
            <Modal
                title={chargeForm.getFieldValue('operationFlag') === 1 ? '积分充值' : '积分扣减'}
                open={chargeModalOpen}
                width={680}
                onOk={chargeForm.submit}
                onCancel={hideChargeModal}
                maskClosable={false}
                okText="确认"
                cancelText="取消"
                style={{padding: 24}}
            >
                <Alert
                    message={
                        <span>
                        提示：<span style={{fontWeight: 'bold', color: 'rgb(22, 93, 255)'}}>1元</span> 相当于 <span style={{fontWeight: 'bold', color: 'rgb(248, 172, 89)'}}>100积分</span>
                    </span>}
                    type="info"
                    showIcon
                />
                <Form
                    labelCol={{span: 4}}
                    wrapperCol={{span: 14}}
                    layout="horizontal"
                    form={chargeForm}
                    style={{maxWidth: 600, marginTop: 24}}
                    onFinish={(values) => submitChargeForm(values)}
                >
                    <Form.Item
                        name="id"
                        hidden
                    />
                    <Form.Item
                        name="operationFlag"
                        hidden
                    />
                    <Form.Item
                        label={chargeForm.getFieldValue('operationFlag') === 1 ? '充值对象' : '扣减对象'}
                    >
                        <span>{chargeObj?.carCode}</span>
                    </Form.Item>
                    <Form.Item
                        label="联系电话"
                    >
                        <span>{chargeObj?.tel}</span>
                    </Form.Item>
                    <Form.Item
                        label={chargeForm.getFieldValue('operationFlag') === 1 ? '充值积分' : '扣减积分'}
                        name="pointBalance"
                        rules={[{required: true, message: '请输入'}]}
                    >
                        <InputNumber style={{ width: '100%' }} min={0} placeholder='请输入' />
                    </Form.Item>
                </Form>
            </Modal>
        </PageContainer>
    );
};

export default connect(({integral}) => {
    return {...integral}
})(TableList);
